import React, { useState,useEffect } from 'react'
import Header from '../../components/Header/Header'
import { reqCate, reqGoods, reqGroupon, reqNew, reqSeck } from '../../request/api'
import './Home.less'
import { FireFill } from 'antd-mobile-icons'
import { countTime } from '../../filters'

import Goods from './components/Goods/Goods'
import Groupon from './components/Groupon/Groupon'
import New from './components/New/New'
import Seckill from './components/Seckill/Seckill'
import { Link } from 'react-router-dom'

const Home=()=>{
  const [news, setNews] = useState([]);
  const [goods, setGoods] = useState([]);
  const [groupon, setGroupon] = useState([]);
  const [seckill, setSeckill] = useState([]);
  const [cates, setCates] = useState([]);
  const [n, setN] = useState(0);
  const [timeArr, setTimeArr] = useState({
    h:0,
    m:0,
    s:0
  });
  // 一进入页面就发请求
  useEffect(()=>{
    // 新人专享
    reqNew().then(res=>{
      setNews(res.data.list);
    });
    // 首页商品
    reqGoods().then(res=>{
      setGoods(res.data.list);
    })
    // 万人团
    reqGroupon().then(res=>{
      setGroupon(res.data.list);
    })
    // 秒杀
    reqSeck().then(res=>{
      setSeckill(res.data.list);
    })
    // 商品分类
    reqCate().then(res=>{
      setCates(res.data.list);
    })
    // 倒计时
    let countTimes=countTime('2022-05-30')
    // console.log(times)
    let timer=null;
    if(countTimes.leftTime>0){
      timer=setInterval(()=>{
        countTimes=countTime('2022-05-30')  
        countTimes.flag=true;
        setTimeArr(countTimes);
      },1000);
    }else{
      clearInterval(timer)
    }
    // 销毁之前清除定时器
    return ()=>{
        clearInterval(timer);
    }
  },[])

  return (
    <div className='home'>
    {/* 1.公共头部 */}
    <Header title="首页"></Header>
    {/* 2.新人专享 */}
    <New news={news} timeArr={timeArr}></New>
    {/* 3.导航栏 */}
    <div className='nav'>
      {cates.length > 0 ? <>
        {cates.map(item => {
          return <Link to="/index/cate" className='item' key={item.id}>
            <span><FireFill /></span>
            <p>{item.catename}</p>
          </Link>
        })}
      </> : null}
    </div>
    {/* 4.秒杀 */}
    <Seckill seckill={seckill} timeArr={timeArr}></Seckill>
    {/* 5.万人团 */}
    <Groupon groupon={groupon} timeArr={timeArr}></Groupon>
    {/* 6.首页商品列表 */}
    <Goods goods={goods} n={n} changeN={(n) => setN(n)}></Goods>
  </div>
  )
}
export default Home;